package com.sfzd5.exam;

import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft;
import org.java_websocket.drafts.Draft_6455;
import org.java_websocket.handshake.ServerHandshake;

import java.net.URI;
import java.net.URISyntaxException;

public class WsClient {
    String location;
    public WsClient(String location){
        this.location = location;
    }

    public WSOpenListener wsOpenListener;
    public WSMessageListener wsMessageListener;

    Draft d = new Draft_6455();

    WebSocketClient cc;

    public void send(String msg){
        cc.send(msg);
    }

    public void close() {
        if (cc != null) {
            cc.close();
        }
    }

    public void start() {
        try {
            // cc = new ChatClient(new URI(uriField.getText()), area, ( Draft ) draft.getSelectedItem() );
            cc = new WebSocketClient(new URI(location), d) {

                @Override
                public void onOpen(ServerHandshake serverHandshake) {
                    if(wsOpenListener!=null){
                        wsOpenListener.onWSOpen(false);
                    }
                }

                @Override
                public void onMessage(String s) {
                    if(wsMessageListener!=null){
                        wsMessageListener.onWSMessage(s);
                    }
                }

                @Override
                public void onClose(int i, String s, boolean b) {

                }

                @Override
                public void onError(Exception e) {
                    if(wsOpenListener!=null){
                        wsOpenListener.onWSOpen(true);
                    }
                }
            };
            cc.connect();

            System.out.println("连接成功");

        } catch (URISyntaxException ex) {

        }
    }
}
